package phone.qyg.com.qyg.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.baidu.location.MyOrientationListener;
import com.app.base.tool.BaseFragment;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.ActivityDetailActivity;
import phone.qyg.com.qyg.activity.FindAddressActivity;
import phone.qyg.com.qyg.activity.FintnessLineMapActivity;
import phone.qyg.com.qyg.activity.VenuesDetailActivity;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.MapIcon;
import phone.qyg.com.qyg.model.MapItem;
import phone.qyg.com.qyg.model.baidu.TranInfo;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.PopuType;

/**
 * 作者：lblbh on 2017/11/28 10:53
 * 邮箱：lanbuhan@163.com
 * 功能：地图
 */
public class MapFragment extends BaseFragment {

    String PARCELABLE_FITNESS = "PARCELABLE_FITNESS";

    @ViewInject(R.id.bmapView)
    MapView bmapView;

    @ViewInject(R.id.find_edit)
    EditText find_edit;

    @ViewInject(R.id.find)
    TextView find;

    @ViewInject(R.id.type_popu)
    TextView type_popu;

    @ViewInject(R.id.type_view)
    TextView type_view;

    @ViewInject(R.id.home_map_detail_layout)
    LinearLayout home_map_detail_layout;

    @ViewInject(R.id.time_layout)
    LinearLayout time_layout;

    @ViewInject(R.id.one_rela)
    RelativeLayout one_rela;

    @ViewInject(R.id.two_rela)
    RelativeLayout two_rela;

    @ViewInject(R.id.three_rela)
    RelativeLayout three_rela;

    @ViewInject(R.id.bottom_detail_layout)
    RelativeLayout bottom_detail_layout;

    @ViewInject(R.id.item_img)
    ImageView item_img;

    @ViewInject(R.id.item_title)
    TextView item_title;

    @ViewInject(R.id.distance)
    TextView distance;

    @ViewInject(R.id.phone)
    TextView phone;

    @ViewInject(R.id.time_one)
    TextView time_one;

    @ViewInject(R.id.time_two)
    TextView time_two;

    @ViewInject(R.id.state)
    TextView state;

    @ViewInject(R.id.address)
    TextView address;

    @ViewInject(R.id.item_discount)
    TextView item_discount;

    @ViewInject(R.id.item_discount_key)
    TextView item_discount_key;

    // 定位相关
    private LocationClient mLocationClient;
    private MyLocationListener mLocationListener;
    private boolean isFirstIn = true;
    private double mLatitude;
    private double mLongtitude;
    // 自定义定位图标
    MyLocationConfiguration.LocationMode mLocationMode;
    MyOrientationListener myOrientationListener;
    BitmapDescriptor mIconLocation;
    float mCurrentX;

    //功能属性
    Map<Integer,View> mapBitmapImg = new HashMap<Integer,View>();

    String httpLongitude;//网络请求使用的坐标

    String httpLatitude;//网络请求使用的坐标

    String coreLongitude;//中心的坐标

    String coreLatitude;//中心的坐标

    String cureentAddress;//当前位置

    List<MapItem> mapItems;

    List<MapIcon> icons;

    List<Base> types;

    Base type;

    MapItem mapItem;

    MapItem oldMapItem;

    Marker oldMarket;

    BaiduMap mBaiduMap;

    boolean isIconEmpty;//图标加载结果

    boolean isShowToast;//显示提示信息

    List<OverlayOptions> allOptions;

    Map<OverlayOptions,MapItem> mapOverFit;

    @Override
    public View initView(LayoutInflater inflater) {
        View view = View.inflate(ct, R.layout.home_map,null);
        x.view().inject(this,view);
        return view;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        initTypes();

        initBMapView();

        initLocation();

        //点击覆盖物
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Bundle bundle = marker.getExtraInfo();
                if(bundle == null)return false;
                mapItem =  bundle.getParcelable(PARCELABLE_FITNESS);
                if(mapItem == null) return false;

                if(oldMarket != marker){
                    if(null != oldMarket){
                        BitmapDescriptor itemMarker = BitmapDescriptorFactory.fromView(mapBitmapImg.get(oldMapItem.objectType));
                        oldMarket.setIcon(itemMarker);
                    }

                    View view = View.inflate(QXApplication.getContext(),R.layout.baidu_select_img,null);
                    BitmapDescriptor selectMarker = BitmapDescriptorFactory.fromView(view);
                    marker.setIcon(selectMarker);

                    oldMarket = marker;
                    oldMapItem = mapItem;
                }

                setBottomState(mapItem.objectType);
                setBottomData();
                home_map_detail_layout.setVisibility(View.VISIBLE);
                return true;
            }
        });

        //点击空白处
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                home_map_detail_layout.setVisibility(View.GONE);
                if((null != oldMarket) && (null != oldMapItem)){
                    BitmapDescriptor itemMarker = BitmapDescriptorFactory.fromView(mapBitmapImg.get(oldMapItem.objectType));
                    oldMarket.setIcon(itemMarker);
                    oldMarket = null;
                    oldMapItem = null;
                }

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        find_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    find();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //可见时执行的操作
            isShowToast = true;
            fMapKeys.put(AppHttpKey.LONGITUDE,String.valueOf(mLongtitude));
            fMapKeys.put(AppHttpKey.LATITUDE,String.valueOf(mLatitude));
            getFitnessItem();
        } else {
            //不可见时执行的操作
            isShowToast = false;
        }
    }

    private void initTypes() {
        String appInfo = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");
        if(isRequestStr(appInfo)){
            types =  JSONTool.jsonDefaluTranClazzs(appInfo,JSONTool.Enum.CULTURE_MAP_TYPE,Base.class);
            icons =  JSONTool.jsonDefaluTranClazzs(appInfo,JSONTool.Enum.BD_MAP_ICO,MapIcon.class);
            getMapIcons();

            //默认type 类型是第一个
            if(isRequestList(types))
                type = types.get(0);
        }else{
            AppHttpRequest.httpAppInfo(new AppHttpRequest.OnAppHttpListener() {
                @Override
                public void onAppHttpState(boolean isState, String result) {
                    if(isState && JSONTool.isStatus(result)){
                        types =  JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.GLOBAL_SEARCH_TYPE,Base.class);
                        icons =  JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.BD_MAP_ICO,MapIcon.class);
                        getMapIcons();

                        if(isRequestList(types))
                            type = types.get(0);
                    }
                }
            });
        }
    }


    private void getMapIcons(){
        new Thread(){
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void run() {
                super.run();
                if(!isRequestList(icons))return;
                for(int i=0,j=icons.size();i<j;i++){
                    MapIcon icon = icons.get(i);
                    View view = View.inflate(QXApplication.getContext(),R.layout.baidu_img,null);
                    ImageView img = (ImageView) view.findViewById(R.id.img);
                    Bitmap bitmap = ImageLoader.getInstance().loadImageSync(ApplicationConfig.NET_DSN_PATH + icon.url);
                    if(bitmap == null){
                        isIconEmpty = true;
                        SystemPrintl.systemPrintl(" bitmap 等于空");
                    }else{
                        isIconEmpty = false;
                    }
                    img.setBackground(new BitmapDrawable(bitmap));
                    mapBitmapImg.put(icon.id,view);
                }
            }
        }.start();
    }


    private void initBMapView() {
        mBaiduMap = bmapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.5f);
        mBaiduMap.setMapStatus(msu);
    }

    private void initLocation(){

        mLocationMode = MyLocationConfiguration.LocationMode.NORMAL;
        mLocationClient = new LocationClient(ct);
        mLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
        // 初始化图标
//        mIconLocation = BitmapDescriptorFactory
//                .fromResource(R.drawable.navi_map_gps_locked);
        //"
        mIconLocation = BitmapDescriptorFactory.fromPath(ApplicationConfig.NET_DSN_PATH + "/relfile/images/mapIco/venue_ico.png");
        myOrientationListener = new MyOrientationListener(ct);

        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener()
                {
                    @Override
                    public void onOrientationChanged(float x)
                    {
                        mCurrentX = x;
                    }
                });

    }


    private class MyLocationListener implements BDLocationListener
    {
        @Override
        public void onReceiveLocation(final BDLocation location)
        {

            MyLocationData data = new MyLocationData.Builder()
                    .direction(mCurrentX)
                    .accuracy(location.getRadius())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(data);
            // 设置自定义图标
            MyLocationConfiguration config = new MyLocationConfiguration(
                    mLocationMode, true, mIconLocation);
            mBaiduMap.setMyLocationConfigeration(config);

            // 更新经纬度
            mLatitude = location.getLatitude();
            mLongtitude = location.getLongitude();

            if(isFirstIn){
                isFirstIn = false;
                LatLng latLng = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(msu);

                cureentAddress = location.getAddrStr();

                SystemPrintl.systemPrintl("当前的地址是---->>>"+cureentAddress);
            }
        }

        public void onConnectHotSpotMessage(String s, int i) {}

    }


    /**
     * 类型搜索
    */
    private void getFitnessItem(){
        if(null == type){
            SystemPrintl.systemPrintl("筛分条件为空");
            return;
        }

        httpLongitude = fMapKeys.get(AppHttpKey.LONGITUDE);
        httpLatitude = fMapKeys.get(AppHttpKey.LATITUDE);

        fMapKeys.put(AppHttpKey.TYPE,String.valueOf(type.id));

        Xutils.GetMap(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.CULTURE_MAP_LIST,
                fMapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        if(!JSONTool.isStatus(result))return;

                        if(!isRequestStr(JSONTool.requestJSONfindName(result,JSONTool.Enum.DATA))){
                            if(isShowToast)
                                PromptManager.showToast(R.string.fitness_hint_empty);
                            return;
                        }

                        mapItems = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.FITRES_LIST, MapItem.class);

                        coreLatitude = JSONTool.jsonDefaluTranString(result,JSONTool.Enum.CEN_LATITUDE);
                        coreLongitude = JSONTool.jsonDefaluTranString(result,JSONTool.Enum.CEN_LONGITUDE);
                        if(!isRequestList(mapItems)){
                            if(isShowToast)
                                PromptManager.showToast(R.string.fitness_hint_empty);
                            mBaiduMap.clear();

                            LatLng httpLatLng = new LatLng(Double.valueOf(httpLatitude),Double.valueOf(httpLongitude));
                            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(httpLatLng);
                            mBaiduMap.animateMapStatus(msu);
//                            return;
                        }

                        addOverlays(mapItems);
                    }
                });
    }


    /**
     * 添加覆盖物
     *
     */
    private void addOverlays(List<MapItem> mapItems)
    {
        mBaiduMap.clear();

        LatLng coreLatLng = new LatLng(Double.valueOf(coreLatitude),Double.valueOf(coreLongitude));

        allOptions = new ArrayList<OverlayOptions>();
        mapOverFit = new HashMap<OverlayOptions,MapItem>();
        if(isRequestList(mapItems)){
            for (MapItem item : mapItems){
                // 经纬度
                String latitude = item.latitude;
                String longitude = item.longitude;
                LatLng latLng = new LatLng(Float.valueOf(latitude), Float.valueOf(longitude));

                // 图标
                View view = mapBitmapImg.get(item.objectType);
                BitmapDescriptor mMarker = BitmapDescriptorFactory.fromView(view);
                OverlayOptions options = new MarkerOptions().position(latLng).icon(mMarker)
                        .zIndex(5);
//
                Marker marker = (Marker) mBaiduMap.addOverlay(options);
                Bundle arg0 = new Bundle();
                arg0.putParcelable(PARCELABLE_FITNESS, item);
                marker.setExtraInfo(arg0);
            }

        }

        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(coreLatLng);
        mBaiduMap.setMapStatus(msu);
    }


    /**
     * 处理底部显示
     * @param type
     */
    private void setBottomState(int type){
        switch (type){
            case 1:
                //场馆
                phone.setVisibility(View.VISIBLE);
                time_one.setVisibility(View.VISIBLE);
                time_layout.setVisibility(View.GONE);
                item_discount.setVisibility(View.VISIBLE);
                item_discount_key.setVisibility(View.VISIBLE);
                break;
            case 2:
                //活动
                phone.setVisibility(View.GONE);
                time_one.setVisibility(View.GONE);
                time_layout.setVisibility(View.VISIBLE);
                item_discount.setVisibility(View.GONE);
                item_discount_key.setVisibility(View.GONE);
                break;
        }
    }

    private void setBottomData(){
        int type = mapItem.objectType;
        ImageLoader.getInstance().displayImage(mapItem.fixImgUrl,item_img, OptionImageUtils.getRectRatio43());
        item_title.setText(setAttributeText(mapItem.title));
        distance.setText(setAttributeText(mapItem.distance));
        phone.setText(setAttributeText(mapItem.phone));
        time_one.setText(setAttributeText(mapItem.phone));
        address.setText(setAttributeText(mapItem.address));
        switch (type){
            case 1:
                //场馆
                time_one.setText(setAttributeText(mapItem.offHour));
                int actCount = mapItem.actCount;
                item_discount.setText(setAttributeText(String.valueOf(mapItem.actCount)));
                item_discount.setVisibility(((actCount == 0)?View.GONE:View.VISIBLE));
                item_discount_key.setVisibility(((actCount == 0)?View.GONE:View.VISIBLE));
                break;
            case 2:
                //活动
                time_two.setText(setAttributeText(mapItem.startTime));
                String statusName = mapItem.statusName;
                state.setText(setAttributeText(mapItem.statusName));
                state.setVisibility((isRequestStr(statusName))?View.VISIBLE:View.GONE);
                String color = mapItem.color;
                if(!isRequestStr(color))return;
                state.setTextColor(Color.parseColor(color));
//                GradientDrawable background = (GradientDrawable) state.getBackground();
//                background.setStroke(CommonUtil.dip2px(QXApplication.getContext(),1),Color.parseColor(color));
                break;
        }
    }


    @Event(value = {R.id.one_rela,R.id.two_rela,R.id.three_rela,R.id.bottom_detail_layout,
                    R.id.find,R.id.type_popu})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.one_rela:
                LatLng  oneLatLng = new LatLng(mLatitude, mLongtitude);

                if(oneLatLng == null) return;

                TransformController.transformControllerModel(QXApplication.getContext(),
                        FintnessLineMapActivity.class,
                        new TranInfo(Double.valueOf(mapItem.latitude),
                                Double.valueOf(mapItem.longitude),
                                oneLatLng.latitude,
                                oneLatLng.longitude,
                                mapItem.address,
                                cureentAddress,
                                0));
                        break;

            case R.id.two_rela:
                LatLng twoLatLng = new LatLng(mLatitude, mLongtitude);
                if(twoLatLng == null) return;

                TransformController.transformControllerModel(QXApplication.getContext(),
                        FintnessLineMapActivity.class,
                        new TranInfo(Double.valueOf(mapItem.latitude),
                                Double.valueOf(mapItem.longitude),
                                twoLatLng.latitude,
                                twoLatLng.longitude,
                                mapItem.address,
                                cureentAddress,
                                1));
                break;
            case R.id.three_rela:
                Bundle bundle = new Bundle();
                bundle.putInt(TransformController.ChangeKEY.BUNDLE_KEY,ApplicationConfig.PERIPHERY_TYPE);
                bundle.putInt(TransformController.ChangeKEY.FIT_MAP_REQUEST,ApplicationConfig.FIT_MAP_TYPE);
                bundle.putParcelable(TransformController.ChangeKEY.FITNESSMAP,mapItem);
                TransformController.transformControllerIntPut((Activity) ct,
                        FindAddressActivity.class,
                        bundle);
                break;
            case R.id.bottom_detail_layout:
                if(null == mapItem)return;
                int itemType = mapItem.objectType;
                Class clazz = null;
                if(itemType == 1){
                    //场馆
                    clazz = VenuesDetailActivity.class;
                }else if(itemType == 2){
                    //活动
                    clazz = ActivityDetailActivity.class;
                }

                if(null != clazz)
                    TransformController.transformControllerModel(QXApplication.getContext(),clazz,mapItem);
                break;
            case R.id.find:
                find();
                break;
            case R.id.type_popu:
                PopuType.setPopuThemes((Activity) ct, type_popu, types, type, new PopuType.OnClickState() {
                    @Override
                    public void OnItemClick(Object model) {
                        Base base = (Base) model;
                        type = base;
                        type_view.setText(type.title);
                    }
                });
                break;
        }
    }

    private void find(){
        String key = find_edit.getText().toString();

        if(!isRequestStr(key) || key.equals(getString(R.string.map_hint_find))){
            PromptManager.showToast(R.string.please_add_find_key);
            return;
        }

        fMapKeys.put(AppHttpKey.NAME,key);
        fMapKeys.put(AppHttpKey.LONGITUDE,String.valueOf(mLongtitude));
        fMapKeys.put(AppHttpKey.LATITUDE,String.valueOf(mLatitude));

        getFitnessItem();
    }

    @Override
    public void onStart() {
        super.onStart();
        // 开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted())
            mLocationClient.start();
        // 开启方向传感器
        myOrientationListener.start();
    }

    public void onPause() {
        super.onPause();
        // 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        bmapView.onResume();
    }


    @Override
    public void onNetChange(int netMobile) {}
}
